package org.agora.photogallery.client;

import org.agora.photogallery.client.event.ShowGalleryEvent;
import org.agora.photogallery.client.presenter.GalleryPresenter;
import org.agora.photogallery.client.presenter.PhotoCollectionPresenter;
import org.agora.photogallery.client.presenter.PhotoPresenter;
import org.agora.photogallery.client.presenter.Presenter;
import org.agora.photogallery.client.view.MainView;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;

public class AppController implements ValueChangeHandler<String>,Presenter{

	private final HandlerManager handlerManager;
	private  HasWidgets container;
	private final MainView view;
	private final GalleryPresenter galleryPresenter;
	private final PhotoPresenter photoPresenter;
	private final PhotoCollectionPresenter photoCollectionPresenter;
	private final HandlerManager eventBus;
	@Inject
	public AppController(HandlerManager handler, MainView view, GalleryPresenter gp, PhotoPresenter pp, PhotoCollectionPresenter pcp, HandlerManager eventBus){
		this.handlerManager = handler;
		this.view = view;
		galleryPresenter = gp;
		photoCollectionPresenter = pcp;
		photoPresenter = pp;
		this.eventBus = eventBus; 
		bind();
	}
	
	private void bind(){
		History.addValueChangeHandler(this);
		
	}
	@Override
	public void present(HasWidgets container) {
		this.container = container;
		galleryPresenter.present(view.getGalleryContainer());
		photoPresenter.present(view.getPhotoContainer());
		photoCollectionPresenter.present(view.getPhotoCollectionContainer());
		container.add(view.asWidget());
		
		if("".equals(History.getToken())){
			History.newItem("GalleryList");
		} else {
			History.fireCurrentHistoryState();
		}
		
		
		
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		if(event.getValue().startsWith("gallery")){
			String id = event.getValue().split("=")[1];
			photoCollectionPresenter.loadGallery(id);
		} else if(token.equals("GalleryList"));
		eventBus.fireEvent(new ShowGalleryEvent());
	}

}
